package com.bookkeeping.cn.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Base64Util {
    public static String encodeImageToBase64(String imagePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        return encodeBitmapToBase64(bitmap);
    }

    public static String encodeBitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
  //将字节进行base64加密
    public static String byte2String(byte[] source) throws UnsupportedEncodingException {
        byte[] encodeBase64 = new byte[0];

        try {
            encodeBase64 = Base64.encode(source, 2);
        } catch (Exception var3) {
            var3.printStackTrace();
        }
        return URLEncoder.encode(new String(encodeBase64), "utf-8");
    }


    public static byte[] reaFileFromSDcard(String path) {
        FileInputStream in = null;
        BufferedInputStream bufferedInputStream = null;
        byte[] result = null;

        try {
            in = new FileInputStream(new File(path));
            bufferedInputStream = new BufferedInputStream(in);
            result = new byte[in.available()];
            int byteSize = bufferedInputStream.read(result);
            Log.d("TAG", "reaFileFromSDcard: byteSize" + byteSize);
        } catch (IOException var17) {
            var17.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException var16) {
                    var16.printStackTrace();
                }
            }

            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException var15) {
                    var15.printStackTrace();
                }
            }

        }

        return result;
    }
}
